import { message } from "@/utils/message";
import { reactive, ref, onMounted, computed, onActivated, nextTick } from "vue";
import { getAgentConsumptionStatistics } from "@/api/ads";
import type {
  FilterFormProps,
  StatisticsResponse,
  FilterOptionsResponse,
  AgentInfo,
  TableRowData,
  SummaryData
} from "./types";

export function useAgentConsumptionStatistics() {
  // 计算默认最近一周的日期范围
  const getLastSevenDays = () => {
    const today = new Date();
    const lastWeek = new Date(today);
    lastWeek.setDate(today.getDate() - 6); // 最近7天：今天往前推6天
    
    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    return [formatDate(lastWeek), formatDate(today)];
  };

  // 筛选表单
  const form = reactive<FilterFormProps>({
    date_range: getLastSevenDays(), // 默认选择最近一周
    department_ids: [],
    platform_ids: [],
    ad_plan_id: 0 // 默认选中计划1
  });

  // 快速选择字段
  const quickSelect = ref('7day');

  const formRef = ref();
  const tableRef = ref();
  const loading = ref(true);
  const agents = ref<AgentInfo[]>([]);
  const dataList = ref<TableRowData[]>([]);
  const summary = ref<SummaryData>({});

  // 筛选选项
  const filterOptions = ref<FilterOptionsResponse>({
    department_options: [],
    platform_options: [],
    ad_plan_options: []
  });

  /** 获取统计数据（包含筛选选项） */
  async function getStatisticsData() {
    loading.value = true;
    try {
      const params: any = {};

      // 处理日期范围
      if (form.date_range && form.date_range.length === 2) {
        params.date_range = form.date_range;
      }

      // 处理投放组筛选
      if (form.department_ids && form.department_ids.length > 0) {
        params.department_ids = form.department_ids;
      }

      // 处理平台筛选
      if (form.platform_ids && form.platform_ids.length > 0) {
        params.platform_ids = form.platform_ids;
      }

      // 处理广告计划筛选
      if (form.ad_plan_id !== undefined && form.ad_plan_id !== null) {
        params.ad_plan_id = form.ad_plan_id;
      }

      const response = await getAgentConsumptionStatistics(params);

      // 检查响应是否成功
      if (!response.success) {
        throw new Error(response.message || '获取数据失败');
      }

      // 统计数据 - 修正数据路径
      const originalData = response.data?.data?.table_data || [];
      agents.value = response.data?.data?.agents || [];
      summary.value = response.data?.data?.summary || {};
      
      // 为每一行计算每日总计
      const dataWithDailyTotal = originalData.map(row => {
        let dailyTotal = 0;
        if (row.agents) {
          Object.values(row.agents).forEach((agentData: any) => {
            dailyTotal += parseFloat(agentData.amount || 0);
          });
        }
        return {
          ...row,
          daily_total: dailyTotal.toFixed(2)
        };
      });
      
      // 如果有汇总数据，在最后加一行总计
      if (dataWithDailyTotal.length > 0 && summary.value && Object.keys(summary.value).length > 0) {
        // 计算所有代理商的总计
        let grandTotal = 0;
        Object.values(summary.value).forEach((agentData: any) => {
          grandTotal += parseFloat(agentData.amount || 0);
        });
        
        const summaryRow = {
          date_formatted: '总计',
          is_summary: true,
          agents: summary.value,
          daily_total: grandTotal.toFixed(2)
        };
        dataList.value = [...dataWithDailyTotal, summaryRow];
      } else {
        dataList.value = dataWithDailyTotal;
      }

      // 筛选选项 - 修正数据路径
      filterOptions.value = {
        department_options: response.data?.department_options || [],
        platform_options: response.data?.platform_options || [],
        ad_plan_options: response.data?.ad_plan_options || []
      };
    } catch (error) {
      console.error("获取统计数据失败:", error);
      message("获取统计数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  /** 搜索 */
  function onSearch() {
    getStatisticsData();
  }

  /** 时间快速选择 */
  function selectTimeRange(value: string) {
    const today = new Date();
    const formatDate = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    switch (value) {
      case 'today': {
        form.date_range = [formatDate(today), formatDate(today)];
        break;
      }
      case 'yesterday': {
        const yesterday = new Date(today);
        yesterday.setDate(today.getDate() - 1);
        form.date_range = [formatDate(yesterday), formatDate(yesterday)];
        break;
      }
      case '7day': {
        const lastWeek = new Date(today);
        lastWeek.setDate(today.getDate() - 6);
        form.date_range = [formatDate(lastWeek), formatDate(today)];
        break;
      }
      case '30day': {
        const lastMonth = new Date(today);
        lastMonth.setDate(today.getDate() - 29);
        form.date_range = [formatDate(lastMonth), formatDate(today)];
        break;
      }
      case 'month': {
        const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
        const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        form.date_range = [formatDate(firstDayOfMonth), formatDate(lastDayOfMonth)];
        break;
      }
      case 'lastmonth': {
        const firstDayOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
        const lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
        form.date_range = [formatDate(firstDayOfLastMonth), formatDate(lastDayOfLastMonth)];
        break;
      }
      case 'diy':
      default: {
        // 自定义，不做处理
        return;
      }
    }
    
    // 除了自定义选择，其他都自动查询
    getStatisticsData();
  }

  /** 日期变化处理 */
  function handleDateChange() {
    quickSelect.value = 'diy';
  }

  /** 重置筛选条件 */
  function resetForm() {
    form.date_range = getLastSevenDays();
    form.department_ids = [];
    form.platform_ids = [];
    form.ad_plan_id = 0; // 重置时默认选中计划1
    quickSelect.value = '7day';
    getStatisticsData();
  }

  /** 刷新数据 */
  function refreshData() {
    getStatisticsData();
  }

  /** 合并汇总行到表格数据 */
  const tableDataWithSummary = computed(() => {
    if (!dataList.value.length || !summary.value || Object.keys(summary.value).length === 0) {
      return dataList.value;
    }

    // 构建汇总行
    const summaryRow = {
      date_formatted: '总计',
      is_summary: true,
      agents: summary.value
    };

    return [...dataList.value, summaryRow];
  });

  /** 表格行样式 */
  const getRowClassName = ({ row }) => {
    return row.is_summary ? 'summary-row' : '';
  };

  /** 页面激活时重新渲染表格 */
  onActivated(() => {
    nextTick(() => {
      if (tableRef.value) {
        tableRef.value.doLayout();
      }
    });
  });

  /** 初始化 */
  onMounted(async () => {
    await getStatisticsData();
    
    // 确保表格正确渲染
    nextTick(() => {
      if (tableRef.value) {
        tableRef.value.doLayout();
      }
    });
  });

  return {
    form,
    formRef,
    tableRef,
    loading,
    agents,
    dataList,
    summary,
    filterOptions,
    quickSelect,
    tableDataWithSummary,
    getRowClassName,
    selectTimeRange,
    handleDateChange,
    onSearch,
    resetForm,
    refreshData
  };
}
